jQuery(function($){
	$("#goPayCenter").click(function(){
		var goPayCenter = this;
		Login.isLogined(function(result){
			if (!result.user_id) {
				Login.show_div();
				return false;
			}
			location.href = goPayCenter.href;
		});
		return false;
	});
	if($("li[name='rec_head']").length == 1 && $("li[rec_id]").length == 0) {
		alert("购物车中无商品");
		location.href = wwwroot;
	}
});
var Goods = Goods || {};
(function(){
	var $ = jQuery;
	var me = this;
	this.add = function(li) {
		var number = parseInt($(li.find("span[name='goods_number']")[0]).text());
		this.updateCart(li, number + 1);
	};
	this.sub = function(li) {
		var number = parseInt($(li.find("span[name='goods_number']")[0]).text());
		if (number == 0) return;
		this.updateCart(li, number - 1);
	};
	this.httpBuildQuery = function(data) {
		var str = "";
		for(var k in data) {
			if(typeof data[k] == "function") continue;
			str += '&' + k + "=" + encodeURIComponent(data[k]);
		}
		return str;
	};
	this.updateCart = function(li,number) {
		var url = wwwroot+"flow.php";
		var data = {
			"step":"aj_update_cart",
			"id":li.attr("rec_id"),
			"number":number
		};

		$.ajax({
			type:"POST",
			url:url,
			cache:false,
			data: me.httpBuildQuery(data), 
			dataType: "json",
			success: function(result) {
				if (result.retcode != 0) {
					alert(result.data.msg);
					return ;
				}
				var preg_price = /\d+(\.\d+)?/;
				// 原来的商品数量
				var old_number = parseInt($(li.find("span[name='goods_number']")[0]).text());
				
				// 变化的商品数量
				var change = number - old_number;
				
				// 更新数量
				$(li.find("input[alias='goods_number']")[0]).val(number);
				$(li.find("span[name='goods_number']")[0]).text(number);
				
				// 更新小计
				var goods_price = parseInt($(li.find("span[name='goods_price']")[0]).text().match(/\d+/g));
				var subtotal = $(li.find("span[name='goods_subtotal']")[0]);
				subtotal.text(subtotal.text().replace(preg_price,number * parseInt(goods_price)));

				// 更新购物车
				updateCartInfo(change);
				
				//更新总计
				var old_content = $("#shopping_money").html();
				var old_money = parseInt(old_content.match(preg_price)[0]);
				var new_money = old_money + (change * goods_price);

				$("#shopping_money").html(old_content.replace(preg_price, new_money));
				
			}
		});	
		


	};
}).call(Goods);

